
(function(window){

	function $(id){
		return document.getElementById(id);
	}

	function on(el, type, fn, that){
		if(el.addEventListener){
			el.addEventListener( type, function(){fn.call(that)}, false);
		}else if(el.attachEvent){
			el.attachEvent('on'+type, fn);
		}else{
			el['on'+type] = fn;
		}
	}

	var input = $('input');
	var left_in = $('left-in');
	var right_in = $('right-in');
	var left_out = $('left-out');
	var right_out = $('right-out');
	var wrap = $('wrap');
	var sort = $('sort');
	var tip = $('tip');

	var chart = {
		num:[],
		text: '',
		_valiadation:function(){
			var temp = input.value.trim();
			if(temp && !isNaN(temp) && temp >= 10 && temp <= 100){
				tip.innerHTML = '';
				return temp;
			}else{
				tip.innerHTML = '请输入10-100之间的数字';
			}
		},
		_count: function(){
			if(this.num.length > 60){
				tip.innerHTML = '队列已满60，不能输入了';
				return true;
			}else{
				tip.innerHTML = '';
			}
		},
		_leftIn: function(){
			
			if(this._valiadation()){
				if(this._count())return;
				this.num.unshift(this._valiadation());
				this._render();
			}
		},
		_rightIn: function(){
			if(this._valiadation()){
				if(this._count())return;
				this.num.push(this._valiadation());
				this._render();
			}
		},
		_leftOut: function(){
			if(this._valiadation()){
				this.num.shift(this._valiadation());
				this._render();
				this._count();
			}
		},
		_rightOut: function(){
			if(this._valiadation()){
				this.num.pop(this._valiadation());
				this._render();
				this._count();
			}
		},
		_render: function(){
			this.text = '';
			for(var i in this.num){
				this.text += '<span style="height:' + this.num[i] + 'px"></span>';
			
			}
			wrap.innerHTML = this.text;
		},
		_sort: function(){
			this.num.sort(function(a, b){
				return a-b;
			});
			this._render();
		},
		_remove: function(e){
			var ev = window.event || e;
			if(ev.target.nodeName.toLowerCase() === 'span'){
				this.num.splice(this.num.indexOf(+ev.target.style.height),1);
				this._render();
				this._count();
			}
		},
		bindEvent: function(){
			// console.log(this._leftIn());
			on(left_in, 'click', this._leftIn,this);
			on(right_in, 'click', this._rightIn,this);
			on(left_out, 'click', this._leftOut,this);
			on(right_out, 'click', this._rightOut,this);
			on(sort, 'click', this._sort,this);
			on(wrap, 'click', this._remove,this);
		},
		init: function(){
			this.bindEvent();
		}
	};
	window.chart = chart;
})(window);

chart.init();